<template>
  <view class="supplies-container">
    <!-- 导航栏 -->
    <nav-bar></nav-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
     
      <view class="nav-right">
        
        <view class="address-btn" @tap="goToAddress">
          <text>收货地址</text>
        </view>
        <view class="order-btn" @tap="goToMyOrders">
          <text>我的</text>
        </view>
      </view>
    </view>

    <!-- 分类标签 -->
    <scroll-view class="category-tabs" scroll-x>
      <view 
        class="tab-item" 
        :class="{ active: currentCategory === category.id }"
        v-for="category in categories" 
        :key="category.id"
        @tap="selectCategory(category.id)"
      >
        {{ category.name }}
      </view>
    </scroll-view>

    <!-- 商品列表 -->
    <scroll-view class="product-list" scroll-y>
      <view class="product-item" v-for="product in products" :key="product.id" @tap="goToDetail(product)">
        <!-- 商品图片 -->
        <image class="product-image" :src="product.image" mode="aspectFit"></image>
        
        <!-- 商品标签 -->
        <view class="product-tag" v-if="product.tag">{{ product.tag }}</view>
        
        <!-- 商品信息 -->
        <view class="product-info">
          <view class="product-title">{{ product.title }}</view>
          <view class="product-notice">{{ product.notice }}</view>
          <view class="product-price">
            <text class="price">¥{{ product.price }}/</text>
            <text class="unit">{{ product.unit }}</text>
          </view>
        </view>

        <!-- 添加按钮 -->
        <view class="add-btn" @tap.stop="addToCart(product)">
          <text class="plus-icon">+</text>
        </view>
      </view>
    </scroll-view>

    <!-- 底部下单按钮 -->
    <view class="bottom-bar">
      <view class="cart-section" @tap="toggleCart">
        <view class="cart-btn">
          <image src="/static/icon/购物车.svg" mode="aspectFit" class="icon-image"></image>
        </view>
        <text class="total-amount">¥{{ totalPrice.toFixed(2) }}</text>
        <view class="cart-badge" v-if="cartTotal > 0">{{ cartTotal }}</view>
      </view>
      <button class="order-btn" @tap="placeOrder">立即下单</button>
    </view>

    <!-- 购物车弹出层 -->
    <view class="cart-popup" v-if="showCart" @tap="toggleCart">
      <view class="cart-content" @tap.stop>
        <view class="cart-header">
          <text class="title">购物车</text>
          <text class="clear" @tap="clearCart">清空</text>
        </view>
        <scroll-view class="cart-list" scroll-y>
          <view class="cart-item" v-for="(item, index) in cartItems" :key="index">
            <image class="item-image" :src="item.image" mode="aspectFill"></image>
            <view class="item-info">
              <text class="item-title">{{ item.title }}</text>
              <text class="item-spec" v-if="item.specifications">规格：{{ item.specifications }}</text>
              <text class="item-price">¥{{ item.price }}</text>
            </view>
            <view class="item-quantity">
              <text class="minus" @tap="decreaseQuantity(index)">-</text>
              <text class="number">{{ item.quantity }}</text>
              <text class="plus" @tap="increaseQuantity(index)">+</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import TechNavBar from '@/components/tech-nav-bar.vue'
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
  components: {
    TechNavBar,
    NavBar
  },
  data() {
    return {
      currentCategory: 'all',
      categories: [],
      products: [],
      cart: [],
      showCart: false,
      cartItems: [],
      loading: false
    }
  },
  async onLoad() {
    await this.getCategories()
    this.getProductList()
    this.loadCartFromLocalStorage()
  },
  onShow() {
    // 每次页面显示时重新加载购物车数据
    this.loadCartFromLocalStorage()
  },
  computed: {
    cartTotal() {
      return this.cartItems.reduce((total, item) => total + item.quantity, 0)
    },
    totalPrice() {
      return this.cartItems.reduce((total, item) => total + item.price * item.quantity, 0)
    }
  },
  methods: {
    // 获取商品分类
    async getCategories() {
      try {
        const res = await uni.request({
          url: `${uni.$config.baseUrl}/system/dict/data/type/supplie_type`,
          method: 'GET'
        })
        
        if (res.statusCode === 200 && res.data.code === 200) {
          // 添加"全部"分类
          this.categories = [
            { id: 'all', name: '全部' },
            ...res.data.data.map(item => ({
              id: item.dictValue,
              name: item.dictLabel
            }))
          ]
        } else {
          uni.showToast({
            title: res.data.msg || '获取分类失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取分类失败:', error)
        uni.showToast({
          title: '获取分类失败',
          icon: 'none'
        })
      }
    },
    
    // 获取商品列表
    async getProductList() {
      if (this.loading) return
      this.loading = true
      
      try {
        const res = await uni.request({
          url: `${uni.$config.baseUrl}/supplies/supplies/listAll`,
          method: 'GET',
          data: {
            status: 1, // 只获取上架商品
            type: this.currentCategory === 'all' ? '' : this.currentCategory
          }
        })
        
        if (res.statusCode === 200 && res.data.code === 200) {
          this.products = res.data.rows.map(item => ({
            id: item.id,
            title: item.title,
            image: item.image,
            tag: item.tag,
            notice: item.notice,
            price: item.price.toString(),
            unit: item.unit,
			type: item.type,
			description: item.description,
			otherImage: item.otherImage,
            specifications: item.specifications,
            stock: item.stock
          }))
        } else {
          uni.showToast({
            title: res.data.msg || '获取商品列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        uni.showToast({
          title: '获取商品列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    selectCategory(categoryId) {
      this.currentCategory = categoryId
      // TODO: 根据分类筛选商品
      this.getProductList()
    },
    addToCart(product) {
		console.log("product",product)
		if("沁心堂工服" === product.title ){
			uni.navigateTo({
			  url: `/pages/technician/supplieDetail?product=${encodeURIComponent(JSON.stringify(product))}`
			})
			return
		}
	
      const existingItem = this.cartItems.find(item => item.id === product.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        this.cartItems.push({
          ...product,
          quantity: 1
        })
      }
      // 保存到localStorage
      this.saveCartToLocalStorage()
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success'
      })
    },
    placeOrder() {
      if (this.cartTotal === 0) {
        uni.showToast({
          title: '请先选择商品',
          icon: 'none'
        })
        return
      }

      // 构造订单商品数据
      const orderItems = this.cartItems.map(item => ({
        id: item.id,
        quantity: item.quantity,
        price: item.price,
        title: item.title,
        image: item.image,
        specifications: item.specifications,
        unit: item.unit
      }))

      uni.navigateTo({
        url: `/pages/technician/supplieOrder?orderItems=${encodeURIComponent(JSON.stringify(orderItems))}`
      })
    },
    goToVouchers() {
      uni.navigateTo({
        url: '/pages/technician/vouchers'
      })
    },
    goToOrders() {
      uni.navigateTo({
        url: '/pages/technician/order-list'
      })
    },
    toggleCart() {
      if (this.cartTotal === 0 && !this.showCart) {
        uni.showToast({
          title: '购物车是空的',
          icon: 'none'
        })
        return
      }
      this.showCart = !this.showCart
    },
    clearCart() {
      this.cartItems = []
      this.showCart = false
      // 保存到localStorage
      this.saveCartToLocalStorage()
    },
    increaseQuantity(index) {
      this.cartItems[index].quantity++
      // 保存到localStorage
      this.saveCartToLocalStorage()
    },
    decreaseQuantity(index) {
      if (this.cartItems[index].quantity > 1) {
        this.cartItems[index].quantity--
      } else {
        this.cartItems.splice(index, 1)
        if (this.cartItems.length === 0) {
          this.showCart = false
        }
      }
      // 保存到localStorage
      this.saveCartToLocalStorage()
    },
    goToDetail(product) {
      uni.navigateTo({
        url: `/pages/technician/supplieDetail?product=${encodeURIComponent(JSON.stringify(product))}`
      })
    },
    goToMyOrders() {
      uni.navigateTo({
        url: '/pages/technician/mysupplieOrder'
      })
    },
    goToAddress() {
      uni.navigateTo({
        url: '/pages/address/address'
      })
    },
    loadCartFromLocalStorage() {
      // 从localStorage加载购物车数据
      try {
        const savedCart = localStorage.getItem('supplieCart')
        if (savedCart) {
          this.cartItems = JSON.parse(savedCart)
        } else {
          this.cartItems = []
        }
      } catch (e) {
        console.error('读取购物车数据失败:', e)
        this.cartItems = []
      }
    },
    saveCartToLocalStorage() {
      // 保存购物车数据到localStorage
      try {
        localStorage.setItem('supplieCart', JSON.stringify(this.cartItems))
      } catch (e) {
        console.error('保存购物车数据失败:', e)
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.supplies-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 120rpx;
  position: relative;
}

.nav-bar {
  position: relative;
  z-index: 100;
  padding: 24rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: flex-start;
  
  .nav-right {
    display: flex;
    gap: 24rpx;
    .address-btn,
    .order-btn {
      display: flex;
      flex-direction: row;
      align-items: center;
      background: #2B87FF;
      padding: 12rpx 24rpx;
      border-radius: 36rpx;
      box-shadow: 0 4rpx 12rpx rgba(43, 135, 255, 0.2);
      transition: all 0.3s ease;
      
      .icon-image {
        width: 40rpx;
        height: 40rpx;
        filter: brightness(0) invert(1);
      }
      
      text {
        font-size: 28rpx;
        color: #FFFFFF;
        margin-left: 8rpx;
        margin-top: 0;
      }

      &:active {
        transform: scale(0.95);
        background: #1A76EE;
      }
    }
  }
}

.category-tabs {
  margin-top: 0;
  background: #FFFFFF;
  white-space: nowrap;
  padding: 24rpx 0;
  border-top: 2rpx solid #F5F5F5;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
  
  .tab-item {
    display: inline-block;
    padding: 12rpx 32rpx;
    margin: 0 12rpx;
    font-size: 32rpx;
    color: #666666;
    border-radius: 36rpx;
    transition: all 0.3s ease;
    
    &.active {
      color: #FFFFFF;
      background: #2B87FF;
      box-shadow: 0 4rpx 8rpx rgba(43, 135, 255, 0.2);
    }
    
    &:first-child {
      margin-left: 24rpx;
    }
    
    &:last-child {
      margin-right: 24rpx;
    }
  }
}

.product-list {
  padding: 24rpx;
  
  .product-item {
    background: #FFFFFF;
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    padding: 24rpx;
    display: flex;
    position: relative;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    transition: transform 0.3s ease;
    
    &:active {
      transform: scale(0.98);
    }
    
    .product-image {
      width: 180rpx;
      height: 180rpx;
      border-radius: 12rpx;
      margin-right: 24rpx;
      object-fit: contain;
      background-color: #f8f8f8;
    }
    
    .product-tag {
      position: absolute;
      left: 24rpx;
      top: 24rpx;
      background: #2B87FF;
      color: #FFFFFF;
      font-size: 24rpx;
      padding: 6rpx 16rpx;
      border-radius: 6rpx;
    }
    
    .product-info {
      flex: 1;
      
      .product-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333333;
        margin-bottom: 12rpx;
      }
      
      .product-notice {
        font-size: 28rpx;
        color: #999999;
        margin-bottom: 20rpx;
      }
      
      .product-price {
        .price {
          font-size: 40rpx;
          color: #FF0000;
          font-weight: bold;
        }
        
        .unit {
          font-size: 28rpx;
          color: #999999;
          margin-left: 4rpx;
        }
      }
    }
    
    .add-btn {
      position: absolute;
      right: 24rpx;
      bottom: 24rpx;
      width: 64rpx;
      height: 64rpx;
      background: #2B87FF;
      border-radius: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 4rpx 8rpx rgba(43, 135, 255, 0.3);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.9);
        background: #1A76EE;
      }
      
      .plus-icon {
        color: #FFFFFF;
        font-size: 44rpx;
        font-weight: 300;
        line-height: 44rpx;
        margin-top: -4rpx;
      }
    }
  }
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 110rpx;
  background: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
  
  .cart-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #2B87FF;
    padding: 12rpx 24rpx;
    border-radius: 50rpx;
    box-shadow: 0 4rpx 12rpx rgba(43, 135, 255, 0.2);
    transition: all 0.3s ease;
    position: relative;
    min-width: 200rpx;
    
    &:active {
      background: #1A76EE;
    }
    
    .cart-btn {
      .icon-image {
        width: 48rpx;
        height: 48rpx;
        filter: brightness(0) invert(1);
      }
    }
    
    .total-amount {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      font-size: 36rpx;
      color: #FFFFFF;
      font-weight: bold;
      }
      
      .cart-badge {
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        background: #FF4B4B;
        color: #FFFFFF;
        font-size: 22rpx;
        min-width: 36rpx;
        height: 36rpx;
        border-radius: 18rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 6rpx;
        box-shadow: 0 2rpx 4rpx rgba(255, 75, 75, 0.3);
    }
  }
  
  .order-btn {
    width: 260rpx;
    height: 84rpx;
    line-height: 84rpx;
    background: #2B87FF;
    color: #FFFFFF;
    font-size: 36rpx;
    border-radius: 42rpx;
    text-align: center;
    margin: 0;
    padding: 0;
    box-shadow: 0 6rpx 12rpx rgba(43, 135, 255, 0.2);
    transition: all 0.3s ease;
    
    &:active {
      transform: scale(0.96);
      background: #1A76EE;
    }
    
    &::after {
      border: none;
    }
  }
}

.cart-popup {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  
  .cart-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background: #FFFFFF;
    border-radius: 24rpx 24rpx 0 0;
    max-height: 80vh;
    box-shadow: 0 -4rpx 24rpx rgba(0, 0, 0, 0.1);
    
    .cart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 36rpx;
      border-bottom: 2rpx solid #F5F5F5;
      
      .title {
        font-size: 36rpx;
        color: #333333;
        font-weight: bold;
      }
      
      .clear {
        font-size: 30rpx;
        color: #2B87FF;
        padding: 8rpx 16rpx;
        
        &:active {
          opacity: 0.8;
        }
      }
    }
    
    .cart-list {
      max-height: calc(80vh - 100rpx);
      
      .cart-item {
        display: flex;
        align-items: center;
        padding: 24rpx 36rpx;
        border-bottom: 2rpx solid #F5F5F5;
        
        .item-image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 12rpx;
          margin-right: 24rpx;
        }
        
        .item-info {
          flex: 1;
          
          .item-title {
            font-size: 32rpx;
            color: #333333;
            margin-bottom: 12rpx;
          }
          
          .item-spec {
            font-size: 30rpx;
            color: #666666;
            margin-bottom: 8rpx;
          }
          
          .item-price {
            font-size: 36rpx;
            color: #2B87FF;
            font-weight: bold;
          }
        }
        
        .item-quantity {
          display: flex;
          align-items: center;
          
          .minus, .plus {
            width: 52rpx;
            height: 52rpx;
            border: 2rpx solid #DDDDDD;
            border-radius: 26rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32rpx;
            color: #333333;
            transition: all 0.2s ease;
            
            &:active {
              background: #F5F5F5;
            }
          }
          
          .plus {
            color: #2B87FF;
            border-color: #2B87FF;
            
            &:active {
              background: rgba(43, 135, 255, 0.1);
            }
          }
          
          .number {
            width: 70rpx;
            text-align: center;
            font-size: 32rpx;
            color: #333333;
          }
        }
      }
    }
  }
}
</style> 